(function() {
	"use strict";
	var app = angular.module("angularApp");
	app.directive("treeMenu", function() {
		return {
			restrict: "E",
			scope: {
				nodeList: '=',
				pnode: "=",
				config:"<?"
			},
			templateUrl: 'common/treeMenu.html',
			controller: function($scope) {
				$scope.selectMenu = $scope.$parent.selectMenu;
			}
		};
	});

	app.config(['$uibModalProvider', function($uibModalProvider) {
		$uibModalProvider.options = { backdrop: 'static', keyboard: false };
	}]);

	//判断是否为空的过滤器
	app.filter('notNull',function(){
		return function(a){
			if(a==null || a==undefined){
				a="无";
			}
			return a;
		}
	});
	app.categories=[{name:"场景管理",powerList:["查看场景","编辑场景"]},
					{name:"分类管理",powerList:["查看样式分类","编辑样式分类"]},
					{name:"图标管理",powerList:["查看图标","编辑图标","下载图标"]},
					{name:"附件管理",powerList:["查看附件","编辑附件","下载附件"]},
					{name:"发布管理",powerList:["查看发布","发布样式"]},
        			{name:"操作日志",powerList:["查看日志","删除日志"]}]

	// 控制器
	app.controller('mainController', function($scope, $rootScope, $location, $q, $http, $uibModal, $state,$cookies,fac) {
		//$scope.menus = appData.menus;
		var menuData;
		$rootScope.scene = {};
		$scope.menuConfig = $scope.menuConfig||{collapse:localStorage.getItem("menuCollapse")=="true"||false};
		$scope.toggleCollapse = function(){
			$scope.menuConfig.collapse = !$scope.menuConfig.collapse;
			localStorage.setItem("menuCollapse",$scope.menuConfig.collapse);
		}
		function getLoginUser() {
			var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
			$http.get("../free/getUserInfo").success(function(resp) {
				if(resp.code == 0){
					app.user = $rootScope.user = resp.data.user;
					$rootScope.elementEnum = resp.data.elementEnum.filter(function(n){return n.type!=0});
					$rootScope.testTypeEnum = resp.data.testTypeEnum;
                    $rootScope.iconTypeEnum = resp.data.iconTypeEnum;
					$rootScope.elementList =$.extend(true,[],$rootScope.elementEnum.filter(function(n){return n.type >0}))

					$rootScope.dictTypeList =[{id:'point',name:'点颜色'},{id:'line',name:'线颜色'},{id:'polygon',name:'面颜色'},{id:'building',name:'楼块颜色'},
					                          {id:'arrow',name:'箭头颜色'},{id:'roadSign',name:'路牌颜色'},{id:'font',name:'字体'},{id:'fontSize',name:'字体大小'}
					                          ,{id:'dashLine',name:'虚线'}]
					// $rootScope.menus = resp.data.menus;
					// menuData = fac.treeToFlat($rootScope.menus);

                    $http.get("../scene/sceneMenu").success(function(resp){
                        if(resp.code == 0){
                            $rootScope.filteredSceneTree = $.extend(true, [],resp.data);
                            $rootScope.allScenes = fac.treeToFlat($rootScope.filteredSceneTree);
                            $rootScope.menus = resp.data;

                            menuData = fac.treeToFlat($rootScope.menus);
                            menuData.forEach(function(n){
                                n.url = "instance/instance?"+n.id;
                            })
                            //选中之前选中的部门
                            var lastSceneId =   localStorage.getItem("lastSceneId");
                            var scene = lastSceneId?menuData.find(function(n){return n.id == lastSceneId}):null;
                            //如果部门为空，当前部门选中第一个根节点！
                            if(!scene && menuData.length>0){
                                scene = menuData.find(function(n){return !n.nodes});
                            }
                            if(scene){
                                $scope.selectMenu(scene);
                            }
                            deferred.resolve(resp.data);
                        }
                    });
				}  else {
					location.href = "login.html";
				}
			})
			return deferred.promise; // 返回承诺，这里并不是最终数据，而是访问最终数据的API
		}

		//退出
		$scope.logout = function() {
			$http.get("../free/logout").success(function(resp) {
				location.href = "login.html";
			})
		};

		//获取所有枚举
		app.loginPromise = getLoginUser();
		app.loginPromise.then(function(){
			//初始化目录列表
            $http.get("../icon/listIconType").success(function(resp){
                if(resp.code === 0){
                    $rootScope.folderList = resp.data;
                }
            })
			/*if("/welcome" == $location.$$url){
				$state.go("welcome");
			}*/
		})

		//  app.modulePromiss = $q.all([app.loginPromise]);
		//  app.modulePromiss =
		//app.modulePromiss = $q.all([deferModule, deferParkTree.promise]);
		$rootScope.$on('$stateChangeSuccess', function (evt, toState, toParams, fromState, fromParams) {
			function toMenu (){
				var item;
				var url = toParams.folder+"/"+(toParams.catalogue?(toParams.catalogue+"/"):"")+toParams.page+(toParams.params?("?"+toParams.params):"");
				item = menuData.find(function(n){return n.url == url});
				if (item) {
					$scope.selectMenu(item);
				}
			}
			if (toParams.folder && toParams.page) {
				app.loginPromise.then(function(user){
					toMenu();
					$scope.curPage = toParams.page;
				})
			}
		})
		$scope.go = function(config){
			$state.go('admin', config);
		}
		$scope.selectMenu = function (node) {
			function _isAncestorNode(parent, son) {
				if(!parent.nodes ){
					return false;
				}else if(parent.nodes.indexOf(son)>-1){
					return true;
				}else{
					return parent.nodes.find(function(n){return _isAncestorNode(n,son)});
				}
			}

			var otherExpandMenu = menuData.find(function (n) {
				return n.expanded == true && n != node && !_isAncestorNode(n, node)
			})
			otherExpandMenu && (otherExpandMenu.expanded = false);

			if (node.nodes && node.nodes.length) {
				node.expanded = !node.expanded;
			} else {
				//展开父节点
				menuData.forEach(function (n) {
					if (_isAncestorNode(n, node)) {
						n.expanded = true;
					}
				})
				//叶子节点
				if ($scope.curMenu && $scope.curMenu != node) {
					$scope.curMenu.selected = false;
				}
				node.selected = true;
				//$location.url(node.url);
				app.powers = node.powers;
				//$state.go(node.url);
				var url = node.url;
				var sceneId = "";
				if(url.indexOf("?")>-1){
					url = node.url.split("?")[0];
					sceneId = node.url.split("?")[1];
					localStorage.setItem("lastSceneId",sceneId);
				}
				var urls = url.split('/');
				if (urls.length === 2) {
                    $scope.$broadcast("closeInstanceDetail");
					$state.go('admin', { folder: urls[0], page: urls[1],id:sceneId });
				} else if (urls.length === 3) {
					$state.go('three', { folder: urls[0], catalogue: urls[1], page: urls[2] });
				}

				$scope.curMenu = node;
				document.body.scrollTop = document.documentElement.scrollTop = 0;
			}
		}

		$scope.uploadXml = function(){
			var modal = $uibModal.open({
				animation: false,
				size:'',
				templateUrl: 'view/instance/instance.upload.html',
				controller: 'instanceUploadCtrl'
					//  ,resolve: {item: angular.extend({},style,{'sceneId':sceneId})}
			});
			modal.result.then(function () {
				//   $scope.find();
				$scope.$broadcast("refreshStyleType");
				//$rootScope.elementEnum && $rootScope.elementEnum.forEach(function(n){ n.pageModel && delete n.pageModel.data});
			}, function () {
				console.info('Modal dismissed at: ' + new Date());
			});
		};
        /*
                $scope.user={
                        account:$cookies.get("account")
                };
                function getUserInfo(){
                    $http({
                        method:'GET',
                        url:'getUserInfo',
                        params:{account:$scope.user.account}
                    }).success(function(data,status,headers,config){
                        console.log("success...");
                        console.log(data);
                        $scope.user=data.data.user;
                    }).error(function(data,status,headers,config){
                        console.log("error...");
                    });
                    return $scope.user;
                }
                var user=getUserInfo();*/

		//展示个人信息
		$scope.showinfo = function (user) {
			console.log(user);
			var modal = $uibModal.open({
				resolve: {
					items:function(){
						return user;
					}
				},
				templateUrl:"userInfo.html",
				controller:function($scope,$uibModal,items){
					$scope.name=items.name;
					$scope.account=items.account;
					$scope.roleId=items.roleId;
					$scope.phone=items.phone;
					$scope.createTime=items.createTime;
					$scope.creator=items.creator;
				}
			});
			modal.result.then(function (node) {
				user.nickname=node.nickname;
				user.userIcon=node.userIcon;
			}, function () {

			});
		}
		//修改密码
		$scope.changePwd = function (user) {
			var modal = $uibModal.open({
				animation: false,
				size:'',
				templateUrl: 'password.html',
				controller: 'changePassword',
				resolve: {user: function(){return user}}
			});
			modal.result.then(function () {
                user.password = user.newPass;
			}, function () {
				console.info('Modal dismissed at: ' + new Date());
			});
		}

		$(document).bind("keydown keypress", function (event) {
			if(event.which === 13) {

				if($("#content").length <= 0 && $("textarea:focus,:button:focus,.btn:focus").length <= 0) {
					var buttons = $(".btn:contains('查询')");
					for(var i=0;i<buttons.length;i++){
						var button = buttons[i];
						if($(button).closest('*:hidden').length){
							continue;
						}
						$(button).trigger("click");
						break;
					}
					event.preventDefault();
				}
			}else if(event.which === 27){
                $("#closePopPhoto").trigger("click");
			}
		});
	});
	app.controller('changePassword', function ($scope,$http,$uibModalInstance,user,fac) {
		$scope.user=user;
		$scope.save = function(form){
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            if(user.newPass!=user.repeatPass){
                alert("两次密码不一致！")
                return;
            }
			//后端交互
			$http.post("changePassword", {oldPass:user.oldPass,newPass:user.newPass},fac.postConfig).success(function(resp){
				if(resp.code===0){
					msg("修改成功！");
                    $uibModalInstance.close();
              /*      $scope.redirect=setTimeout(function(){
                        location.href = "login.html";
                    },1000)*/
				}else{
					alert(resp.msg);
				}
			})
		}
	});
	app.controller('instanceUploadCtrl', function($scope,$http,$uibModalInstance,fac) {
		$scope.item = {};

		$scope.save = function (form) {
			form.$setSubmitted(true);
			if (!form.$valid) {
				return;
			}
			if($scope.filteredSceneTree.find(function(n){return n.id ==$scope.item.sceneId})){
				alert("请选择至少二级及以下场景中！");
				return;
			}
            if(!$scope.item.sceneId){
				$scope.item.sceneName = "";
                alert("请选择场景！");
                return;
            }
			if(!$("#xmlInput").val()){
				alert("请选择样式xml！")
				return false;
			}
			var index = layer.load(1, {
				shade: [0.2, '#000'] //0.1透明度的白色背景
			});
			$("iframe[name='iframe_0']").on("load",function() {
				layer.close(index);
				var contents = $(this).contents().get(0);
				var data = $(contents).find('body').text();
				try{
					data = window.eval('(' + data + ')');
				}catch(e){
					console.log(data)
					if(data ==""){
						data = "请重新登录!";
					}
					data = {code:403,msg:data}
				}
				if (data.code === 0) {
					$uibModalInstance.close();
					msg("保存成功!");
				} else if(data.code === 2){
					var message ="";
                    data.data.forEach(function(n){
                        message +="<p>"+n+"</p>";
					})
                    layer.confirm(message, { btn: ['确定'], title: data.msg }, function (index) {
                        layer.close(index);
                    }, function () {
                    });

				} else{
                    alert(data.msg);
				}

			});
			$("form[name='form']").submit();

		}
	});

})();
